package com.camunda.demo.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : pengjie
 * @version v1.0.0
 * @ClassName : QingJiaController
 * @Description : TODO
 * @email : 627799251@qq.com
 * @Date : 2019/6/28 16:19
 */
@Api
@RestController
@RequestMapping("/qingjia")
public class QingJiaController {

    private final Logger LOGGER = LoggerFactory.getLogger(QingJiaController.class);
    private final TaskService taskService;
    private final RuntimeService runtimeService;


    public QingJiaController(TaskService taskService, RuntimeService runtimeService) {
        this.taskService = taskService;
        this.runtimeService = runtimeService;
    }

    @ApiOperation(value = "请假申请")
    @PostMapping(value = "/{projectId}/users{userId}")
    public boolean ParticipatingProject(@PathVariable Long projectId, @PathVariable Long userId, int leave_days) {
        //ignore argument verify

        //save the record to db

        Long savedRecordId = 3L;
        //start a new instance of the process
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("renshi", "testrenshi");
        variables.put("up_leader", "upleader");
        variables.put("admin", "admin");
        variables.put("leave_days", leave_days);
        variables.put("user", String.valueOf(userId));
        variables.put(ProjectProcessConstant.FORM_RECORD_ID, savedRecordId);

        ProcessInstance instance = runtimeService.startProcessInstanceByKey("qingjiadan", variables);
        if (instance == null) {
            return false;
        }else {
            return true;
        }
    }

    @ApiOperation(value = "获取需要审批的项目申请列表")
    @GetMapping(value = "/approve/list")
    public @ResponseBody
    List<ProjectParticipateRequestRecord> getAllProjectParticipateRequest(String ccGroup) {

        LOGGER.info("The CandidateGroup name is {}", ccGroup);
        //get the taskList
        List<Task> tasks;
        tasks = taskService.createTaskQuery().
                //taskName(ProjectProcessConstant.TASK_NAME_SECOND_LEVEL_REVIEW).
                taskCandidateGroup(ccGroup).
                list();

        List<ProjectParticipateRequestRecord> records = new ArrayList<ProjectParticipateRequestRecord>(tasks.size());
        tasks.forEach( task -> {
            ProjectParticipateRequestRecord record = new ProjectParticipateRequestRecord();
            String taskId = task.getId();
            Map<String, Object> variables = taskService.getVariables(taskId);

            Long studentId = Long.valueOf ( (String)variables.get("user") );
            Long recordId = (Long) variables.get(ProjectProcessConstant.FORM_RECORD_ID);
            record.setStudentId(studentId);
            record.setProjectParticipateId(recordId);
            record.setTaskId(taskId);
            record.setTaskName(task.getName());

            records.add(record);
        });

        return records;
    }

    @ApiOperation(value = "审批请假单")
    @PutMapping(value = "/participateRequests/{taskId}")
        public boolean approveProjectParticipateRequest(@PathVariable String taskId, boolean needExtraInfo, boolean passed, String ccGroup) {
        Task task = taskService.createTaskQuery().
                //taskCandidateGroup(ccGroup).
                taskId(taskId).singleResult();
        if (task == null) {
            LOGGER.error("The task not found, task id is {}", taskId);
            return false;
        }else {
            //business logic here

            //Into next step
            LOGGER.info("The taskId is {}, parent task id is {}", taskId, task.getParentTaskId());
            Map<String, Object> variables = new HashMap<>();
            variables.put("pass", passed);
            variables.put("need_extra", needExtraInfo);
            taskService.complete(task.getId(), variables);
            return true;
        }
    }
}
